﻿//创建时间: 2010-10-19
//创建作者: 李晓忠
//功能说明: CMS系统 内容管理 
//修改: 2010-10-19 
//修改: 2010-10-20 添加可选值的显示。 添加保存功能
//修改: 2010-10-21 添加可选值的显示。 添加修改功能，修改查询模型字段方法。
//修改: 2010-11-16 添加相关文章控件功能。
//修改: 2010-11-19  添加表单值采集功能。
//修改：2011.1.25 李晓忠 添加操作日志记录
//修改：2011.6.16 李城 在当前页面移除了原来冗余的ajax处理，并将这些ajax处理移至content_saveAdvance.aspx页面
//修改：2011.6.16 李城 对当前页面的逻辑处理做了理顺，并加上注释，冗余变量做了删除
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TRPOP.Common;
using TRPOP.CMS.Web.UI;


using TRPOP.CMS.Business;
using TRPOP.CMS.Model;
using Newtonsoft.Json;
using System.Text;
using System.Data;
using TRPOP.CMS.Publish;
namespace TRPOP.CMS.Web.Admin
{
    public partial class content_save : BaseAdmin
    {

        #region 当前页面权限验证
        protected override void SubPageInit()
        {
            base.m_SubPagePermission = Plugin.PermissionKeys.PermissionEnum.Content_AllControl;
        }
        #endregion

        #region 页面变量
        protected int m_intNodeId = 0;
        protected int m_intId = 0;
        protected string m_strNodeName = string.Empty;
        protected NodeInfo m_NodeInfo = new NodeInfo();
        protected NodeManage m_NodeManage = new NodeManage();
        ModelFieldManage m_ModelFieldManage = new ModelFieldManage();
        protected ContentInfo m_ContentInfo = new ContentInfo();
        protected ContentManage m_ContentManage = new ContentManage();
        private ModelInfo m_ModelInfo = new ModelInfo();
        protected string m_strGoToURL = string.Empty;
        protected string m_strAddURL = string.Empty;
        protected string m_strMsg = string.Empty;
        protected string m_strContentTitle = string.Empty;
        protected string m_strURL = string.Empty;
        /// <summary>
        /// 模板的基本路径
        /// </summary>
        protected string strBaseTemplate = SYSConfig.SystemVar_Templatepath;
        #endregion

        #region 页面事件

        protected void Page_Load(object sender, EventArgs e)
        {
            m_intNodeId = RequestHelper.RequestInt("nodeid", 0);
            m_intId = RequestHelper.RequestInt("id", 0);
            if (m_intId <= 0)
            {
                //如果是添加信息，则检查当前版本的权限
                base.AlertForNoPermissionAddContent(m_ContentManage.IsOverFlow());
            }
            if (!IsPostBack)
            {
                LoadBase();
                BindData();
            }
        }

        /// <summary>
        /// 保存信息响应的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // 根据m_intId 加载基本的m_ContentInfo 信息，并日志记录
            // 基本信息初始化
            #region 以上描述的详细代码
            if (m_intId > 0)
            {
                m_ContentInfo = (ContentInfo)GetPageViewState("content");
                m_ContentInfo.UpdateTime = GetAdminAddTime;
                m_ContentInfo.UpdateUserId = base.mUserBaseInfo.UserBaseId;
                base.SaveLog(Plugin.LogKeys.OperObject.InfoOper, Plugin.LogKeys.OperResult.EditSubmit);
            }
            else
            {
                m_ContentInfo.NodeId = m_intNodeId;
                m_ContentInfo.AddTime = GetAdminAddTime;
                m_ContentInfo.AddUserId = base.mUserBaseInfo.UserBaseId;
                m_ContentInfo.PubTime = GetAdminAddTime;
                m_ContentInfo.PubStatus = 0;
                m_ContentInfo.UpdateTime = GetAdminAddTime;
                m_ContentInfo.UpdateUserId = base.mUserBaseInfo.UserBaseId;
                base.SaveLog(Plugin.LogKeys.OperObject.InfoOper, Plugin.LogKeys.OperResult.AddSubmit);
            }
            #endregion

            // 信息基表的信息处理
            #region 以上描述的详细代码
            m_NodeInfo = (NodeInfo)GetPageViewState("nodeinfo");
            m_ContentInfo.ExtraUrl = txtExtraUrl.TextFilterSQL;
            m_ContentInfo.HtmlName = txtHtmlName.TextFilterSQL;
            m_ContentInfo.Name = txtName.TextFilterSQL.RemoveHtml();
            m_ContentInfo.Type = (int)LinkType.EnumElement.RealLink;
            m_ContentInfo.PubUserId = 0;
            m_ContentInfo.ReadLimit = 0;
            m_ContentInfo.SEODescription = txtSEODescription.TextFilterSQL.RemoveHtml();
            m_ContentInfo.SEOKey = txtSEOKey.TextFilterSQL.RemoveHtml();
            m_ContentInfo.SEOTitle = txtSEOTitle.TextFilterSQL.RemoveHtml();
            m_ContentInfo.Status = 0;
            if (!txtTemplate.Text.IsEmpty())
                m_ContentInfo.Template = ("/" + txtTemplateRoot.Value + "/" + txtTemplate.TextFilterSQL).Replace("//", "/").RemoveHtml();//模板
            else
                m_ContentInfo.Template = "";
            m_ContentInfo.TopWeight = txtTopWeight.Text.ToInt();
            m_ContentInfo.EliteWeight = txtEliteWeight.Text.ToInt();
            m_ContentInfo.DisplayOrder = txtDisplayOrder.Text.ToInt();
            m_ContentInfo.SelfPSN = txtSelfPSN.TextFilterSQL;
            m_ContentInfo.SelfURL = txtSelfUrl.TextFilterSQL;
            #endregion

            // 信息扩展表的信息处理
            // 通过 TableName_FieldName 形式的key，获取 Request 页面传递过来的各个参数值
            // 图片本地化
            #region 以上描述的详细代码
            m_ModelInfo = (ModelInfo)GetPageViewState("model");
            List<ModelFieldInfoWithTableName> m_ModelFieldInfoList = (List<ModelFieldInfoWithTableName>)GetPageViewState("modelfieldlist");
            bool BlnGetTableName = false;
            string strFormKey = string.Empty;
            foreach (ModelFieldInfoWithTableName FieldInfo in m_ModelFieldInfoList)
            {
                if (!BlnGetTableName)
                {
                    // 把扩展表明 增加到基本信息里
                    m_ContentInfo.ExtendTableName = FieldInfo.TableName;
                    BlnGetTableName = true;
                }
                strFormKey = FieldInfo.TableName + "_" + FieldInfo.FieldName.ToString();
                if (Request[strFormKey] == null)
                    continue;
                //不同的字段类型，不通的处理
                if (FieldInfo.FieldTypeStr == "varchar" || FieldInfo.FieldTypeStr == "nvarchar")
                {
                    FieldInfo.DefaultValue = StringExtension.CutStringWithByte(Request[strFormKey], FieldInfo.FieldLength).SQLFilter();
                }
                else if (FieldInfo.FieldTypeStr == "bit" || FieldInfo.FieldTypeStr == "int")
                {
                    FieldInfo.DefaultValue = Request[strFormKey].ToString().ToInt().ToString();
                }
                else
                {
                    FieldInfo.DefaultValue = Request[strFormKey].SQLFilter();
                }
                //标题字段的处理
                if (FieldInfo.IsTitleField)
                {
                    m_ContentInfo.Name = Request[strFormKey];
                    m_strContentTitle = Request[strFormKey];
                }
                //如果需要下载远程图片
                if (FieldInfo.IsMainField && Request["chkPicLocating"] != null && Request["chkPicLocating"].ToString().ToBool())//下载远程图片
                {
                    //原来的图片本地化不加水印 FieldInfo.DefaultValue = m_ContentManage.DownContentURLFile(FieldInfo.DefaultValue, m_NodeInfo).SQLFilter();

                    //2011.07.08 图片本地化 加水印
                    bool blsIsWater = false;
                    TRPOP.Common.CMSImageHelper.WaterPicLocation oWaterPicLocationEnum = CMSImageHelper.WaterPicLocation.BottomRight;
                    blsIsWater = TRPOP.Common.CookieHelper.GetCookie("chkPicWater").ToLower() == "true";// Request["chkPicWater"] != null && Request["chkPicWater"].ToString().ToBool();
                    int intWaterPicLoaction = 5;
                    intWaterPicLoaction = TRPOP.Common.CookieHelper.GetCookie("chkPicWaterSelect").ToInt();
                    if (intWaterPicLoaction <= 0 || intWaterPicLoaction > 5)
                        intWaterPicLoaction = 5;
                    oWaterPicLocationEnum = (CMSImageHelper.WaterPicLocation)Enum.ToObject(typeof(CMSImageHelper.WaterPicLocation), intWaterPicLoaction);
                    FieldInfo.DefaultValue = m_ContentManage.DownContentURLFile(FieldInfo.DefaultValue, m_NodeInfo, blsIsWater, oWaterPicLocationEnum);
                }
            }
            #endregion

            //编辑的panel隐藏 提示信息的panel显示
            edit_panel.Visible = false;
            tip_panel.Visible = true;

            //保存信息
            EnumSubmitResult enumResult = m_ContentManage.SaveNewDoc(m_ContentInfo, m_ModelFieldInfoList);

            //将以上传的并且保存在数据库里的ContentUpFileInfo 的 contentid 赋值，保存该ContentUpFileInfo
            #region 以上描述的详细代码
            ContentUpFileManage m_ContentUpFileManage = new ContentUpFileManage();
            foreach (ModelFieldInfoWithTableName FieldInfo in
                                       m_ModelFieldInfoList.FindAll(
                               delegate(ModelFieldInfoWithTableName oTempInfo)
                               {
                                   return (!string.IsNullOrEmpty(oTempInfo.DefaultValue)) &&
                                          ((oTempInfo.FieldInputPicker == FieldInputPickerType.ImgPicker) || (oTempInfo.FieldInputPicker == FieldInputPickerType.AttachPicker));
                               })

                     )
            {
                ContentUpFileInfo m_ContentUpFileInfo = m_ContentUpFileManage.GetInfoByFileRoot(FieldInfo.DefaultValue);
                if (m_ContentUpFileInfo != null)
                {
                    m_ContentUpFileInfo.ContentId = m_ContentInfo.ContentId;
                    m_ContentUpFileManage.Save(m_ContentUpFileInfo);
                }
            }
            #endregion

            //对于编辑器已经上传的文件，保存至附件库中
            m_ContentUpFileManage.SaveEditorUpLoadFile(PageAssist.EditorUpLoadFieldKey, m_NodeInfo, m_ContentInfo.ContentId, base.mUserBaseInfo.UserBaseId);

            //提供给用户的 [继续添加] [重新编辑]... 的页面里用到的变量
            m_strNodeName = m_NodeInfo.Name;
            m_strGoToURL = "content_save.aspx?nodeid=" + m_intNodeId + "&id=" + m_ContentInfo.ContentId;
            //m_intId = m_ContentInfo.ContentId;
            m_strAddURL = "content_save.aspx?nodeid=" + m_intNodeId;
            //m_strURL = m_ContentInfo.Url;

            //*****************  信息保存Success后的额外操作   *****************/
            //如果保存页面成功，则更新相关的信息
            if (enumResult == EnumSubmitResult.Success)
            {
                //生成信息URL，并保存
                m_ContentInfo.Url = m_ContentManage.CreateURL(m_NodeInfo, m_ContentInfo);
                //在页面上更新URL
                m_strURL = m_ContentInfo.Url;
                //发布或更新页面操作
                if (m_NodeInfo.IsAuoPub && m_NodeInfo.ContentPubTypeId != (int)ContentPubType.EnumElement.NotOutPub)
                {
                    PublishAccess.PubOneContentPage(m_ContentInfo.ContentId);
                }
                // 如果添加信息，并且所在结点是实结点，则在与之关联的虚节点上生成虚连接,如果这些虚连接需要发布，则直接发布
                #region 以上描述的详细代码
                if (m_intId == 0 && (m_NodeInfo.NodeTypeId == (int)NodeType.EnumElement.TrueNode))
                {
                    List<NodeInfo> VirualNodeList = m_NodeManage.GetVirualNode(m_NodeInfo.NodeId);
                    foreach (NodeInfo newNodeInfo in VirualNodeList)
                    {
                        bool result = false;
                        string msg = "";
                        List<ContentInfo> m_ContentInfoList = m_ContentManage.CreateVirtualLink(m_NodeInfo.NodeId, newNodeInfo.NodeId, m_ContentInfo.ContentId.ToString(), out result, out msg);
                        if (result && newNodeInfo.IsAuoPub && newNodeInfo.ContentPubTypeId != (int)ContentPubType.EnumElement.NotOutPub)
                        {
                            foreach (ContentInfo minfo in m_ContentInfoList)
                            {
                                PublishAccess.PubOneContentPage(minfo.ContentId);
                            }
                        }
                    }
                }
                #endregion
                m_strMsg += "发布文档添加成功";
            }
            else
            {
                m_strMsg = "发布文档添加失败";
            }
        }


        #endregion

        #region 页面方法

        /// <summary>
        /// 加载基本的信息: 结点信息  模型字段信息
        /// </summary>
        public void LoadBase()
        {
            if (m_intNodeId <= 0)
                return;
            //结点信息不为空 并且结点不隐藏
            if ((m_NodeInfo = m_NodeManage.GetInfoById(m_intNodeId)) != null && m_NodeInfo.IsHidde == false)
            {

                //如果结点类型为不对外不发，则不显示 前台预览
                if (m_NodeInfo.ContentPubTypeId != (int)ContentPubType.EnumElement.NotOutPub)
                {
                    ltPreView.Visible = false;
                }

                //获取结点信息
                m_strNodeName = m_NodeInfo.Name;
                InitPageViewState("nodeinfo", m_NodeInfo);

                //根据结点信息，获取所属内容模型的字段List信息,并将此List信息保存至视图中
                List<ModelFieldInfoWithTableName> m_ModelFieldInfoList = new List<ModelFieldInfoWithTableName>();
                foreach (ModelFieldInfoWithTableName FieldInfo in m_ModelFieldManage.GetWithTableNameListByModelId(m_NodeInfo.ModelId))
                {
                    m_ModelFieldInfoList.Add(FieldInfo.Clone() as ModelFieldInfoWithTableName);
                }
                InitPageViewState("modelfieldlist", m_ModelFieldInfoList);

                //显示内容修改面板
                edit_panel.Visible = true;

                //保存水印图片地址
                base.ExecuteJs("SaveCookieWaterPic('" + m_NodeInfo.WaterPic + "');");
            }
            else
            {
                base.Redirect("../error.aspx?msg=结点不存在");
            }
        }

        /// <summary>
        /// 数据绑定 加载显示的字段
        /// </summary>
        public void BindData()
        {
            List<ModelFieldInfoWithTableName> m_ModelFieldInfoList = (List<ModelFieldInfoWithTableName>)GetPageViewState("modelfieldlist");
            // 如果 m_ModelFieldInfoList 为null，则需重新进入本页面
            if (m_ModelFieldInfoList == null)
            {
                base.ExecuteJsWidthEnd("alert(请重新进入本页面);");
                return;
            }
            //如果信息ID小于等于0，则只需绑定相关的字段就可以了
            if (m_intId <= 0)
            {
                rptFormList.DataSource = m_ModelFieldInfoList.FindAll(delegate(ModelFieldInfoWithTableName oModelFieldInfoWithTableName)
                {
                    return oModelFieldInfoWithTableName.IsEdit == true;
                });
                rptFormList.DataBind();
            }
            else
            {
                m_ContentInfo = m_ContentManage.GetInfoById(m_intId);
                if (m_ContentInfo != null && m_ContentInfo.PubStatus != (int)PubStatus.EnumElement.Delete && m_ContentInfo.NodeId > 0)
                {
                    //将内容基本信息绑定到web控件中，将扩展信息保存至ModelFieldInfoList ， 对动态加载的form元素进行绑定
                    #region 上描述的详细代码
                    InitPageViewState("content", m_ContentInfo);
                    m_NodeInfo = (NodeInfo)GetPageViewState("nodeinfo");
                    if (m_NodeInfo == null)
                    {
                        m_NodeInfo = m_NodeManage.GetInfoById(m_ContentInfo.NodeId);
                    }
                    // ***********************绑定信息
                    //基本信息
                    txtExtraUrl.Text = m_ContentInfo.ExtraUrl;
                    txtHtmlName.Text = m_ContentInfo.HtmlName;
                    txtName.Text = m_ContentInfo.Name;
                    txtSEODescription.Text = m_ContentInfo.SEODescription;
                    txtSEOKey.Text = m_ContentInfo.SEOKey;
                    txtSEOTitle.Text = m_ContentInfo.SEOTitle;
                    txtEliteWeight.Text = m_ContentInfo.EliteWeight.ToString();
                    txtTopWeight.Text = m_ContentInfo.TopWeight.ToString();
                    txtDisplayOrder.Text = m_ContentInfo.DisplayOrder.ToString();
                    txtSelfPSN.Text = m_ContentInfo.SelfPSN;
                    txtSelfUrl.Text = m_ContentInfo.SelfURL;
                    txtUrl.Text = m_ContentInfo.Url;
                    // 模板信息
                    string strTemplate = m_ContentInfo.Template;
                    if (strTemplate.IsEmpty() == false)
                    {
                        if (strTemplate.StartsWith(strBaseTemplate))
                        {
                            strTemplate = strTemplate.Substring(strTemplate.IndexOf(strBaseTemplate) + 10);
                        }
                        txtTemplateRoot.Value = strBaseTemplate;
                    }
                    txtTemplate.Text = strTemplate;
                    // 将原来的内容信息保存至 ModelFieldInfoList ， 然后进行绑定
                    if (m_NodeInfo != null)
                    {
                        m_strNodeName = m_NodeInfo.Name;
                        edit_panel.Visible = true;//显示内容修改面板
                        // 根据结点信息、内容基本信息 获取内容的扩展信息，并将扩展信息保存至 ModelFieldInfoList 并将相关的信息保存至视图中
                        #region  上述说明的详细代码
                        InitPageViewState("nodeinfo", m_NodeInfo);
                        m_ModelInfo = (new ModelManage()).GetInfoById(m_NodeInfo.ModelId);
                        InitPageViewState("model", m_ModelInfo);
                        DataSet ds = m_ContentManage.GetDataSet(m_ModelInfo.TableName, "", " and " + m_ModelInfo.TableName + "id=" + m_ContentInfo.ExtendId, "");
                        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            DataRow oDataRow = ds.Tables[0].Rows[0];
                            foreach (ModelFieldInfoWithTableName FieldInfo in m_ModelFieldInfoList)
                            {
                                if (!ds.Tables[0].Columns.Contains(FieldInfo.FieldName))
                                    continue;
                                //需要查询模型表赋值
                                if (FieldInfo.FieldTypeStr == "bit")
                                {
                                    FieldInfo.DefaultValue = Convert.ToBoolean(oDataRow[FieldInfo.FieldName]) ? "1" : "0";
                                }
                                else
                                {
                                    FieldInfo.DefaultValue = oDataRow[FieldInfo.FieldName].ToString();
                                }
                            }
                        }
                        InitPageViewState("modelfieldlist", m_ModelFieldInfoList);
                        InitPageViewState("modelfieldds", ds);
                        #endregion
                        rptFormList.DataSource = m_ModelFieldInfoList.FindAll(delegate(ModelFieldInfoWithTableName oModelFieldInfoWithTableName)
                        {
                            return oModelFieldInfoWithTableName.IsEdit == true;
                        });
                        rptFormList.DataBind();
                    }
                    #endregion
                }
                else
                {
                    base.Redirect("../error.aspx?msg=要修改的信息不存在");
                    //没有找到信息
                }
            }
            //在这里设置通过编辑器（ckfinder）上传文件所需要的基本信息，保存到session里，供编辑器使用
            //主要的信息有：图片水印(暂时没用到)、保存路径
            if (m_NodeInfo != null)
            {
                JavaScriptObject jsNode = new JavaScriptObject();
                jsNode.Add("NodeId", m_NodeInfo.NodeId);
                jsNode.Add("WaterPic", m_NodeInfo.WaterPic);
                if (m_NodeInfo.SourcePSN != "" && m_NodeInfo.SourceUrl != "")
                {
                    string strSavePath = (new PSNManage()).GetPSNPathByPSN(m_NodeInfo.SourcePSN) + "/" + (new NodeManage()).RootReg(m_NodeInfo.SourceRootReg, DateTime.Now);
                    strSavePath = strSavePath.Replace("//", "/");
                    jsNode.Add("savepath", strSavePath);
                }
                else
                {
                    string strSavePath = (new PSNManage()).GetPSNPathByPSN(SYSConfig.SystemVar_DefaultResourcePSN) + "/";
                    strSavePath = strSavePath.Replace("//", "/");
                    jsNode.Add("savepath", strSavePath);
                }
                jsNode.Add("nodeid", m_NodeInfo.NodeId);
                Session.Add("jsNode", jsNode);
            }
        }

        /// <summary>
        /// 根据某个模型字段的相关信息，输出form表单元素
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="FieldName">字段名</param>
        /// <param name="FieldTypeStr">字段类型</param>
        /// <param name="DefaultValue">字段默认值</param>
        /// <param name="FieldLength">字段长度</param>
        /// <param name="FormInputTypeId">输入类型id</param>
        /// <param name="FormInputLimitTypeId">输入限制id</param>
        /// <param name="FormInputValueTypeId">输入值类型id</param>
        /// <param name="Name">字段标识名</param>
        /// <param name="FieldInputPicker">字段采集器的key</param>
        /// <returns></returns>
        public string BindFormElement(object TableName, object FieldName, object FieldTypeStr, object DefaultValue, object FieldLength, object FormInputTypeId, object FormInputLimitTypeId, object FormInputValueTypeId, object Name, object FieldInputPicker)
        {
            //Form录入类型
            FormInputTypeInfo oFormInputTypeInfo = (new FormInputTypeManage()).GetInfoByIdFromCache(FormInputTypeId.ToString().ToInt());
            if (oFormInputTypeInfo == null)
                return string.Empty;
            //存放form元素html代码的容器
            StringBuilder oStrBuild = new StringBuilder();
            //JSObject实体，获取相关的字段信息
            JavaScriptObject oJsObj = new JavaScriptObject();
            /*
             *    2011.08.17 李城 新增功能
             *    增加多编辑器的功能
             *    如果字段form类型为 ckeditor ，这个时候来根据结点设置的 Editor 来决定前台页面form元素的类型 ckeditor、htmleditor、xheditor
             *        否则，还是按照之前的处理，针对不同的字段form类型来绑定不同的form元素
             */
            //原来的代码
            //oJsObj.Add("type", oFormInputTypeInfo.FormItem);
            //新的代码
            if (oFormInputTypeInfo.FormItem != "ckeditor")
            {
                oJsObj.Add("type", oFormInputTypeInfo.FormItem);
            }
            else
            {
                NodeInfo oNodeInfo = GetPageViewState("nodeinfo") as NodeInfo;
                if (oNodeInfo != null)
                {
                    oJsObj.Add("type", oNodeInfo.Editor.Trim());
                }
                else
                {
                    oJsObj.Add("type", oFormInputTypeInfo.FormItem);
                }
            }
            /*
             *   多编辑器 结束
             */
            string strInputName = TableName.ToString() + "_" + FieldName.ToString();//form元素的name
            string strInputId = TableName.ToString() + "_" + FieldName.ToString();  //form元素的id
            switch (oFormInputTypeInfo.FormItem)
            {
                case "radio":
                    // 如果是radio类型的form元素，则给JSObject添加item元素，item存放着可选值
                    // 如果字段类型是 bit,则添加 是 否
                    // 如果字段类型不是 bit，则动态读取数据库，读出制定的radio可选值，如果为空，则什么也不添加
                    #region radio的详细代码
                    JavaScriptObject jsItems = new JavaScriptObject();
                    if (FieldTypeStr.ToString() == "bit")
                    {
                        //添加 是（1） 
                        JavaScriptObject jsItemY = new JavaScriptObject();
                        jsItemY.Add("text", "是");
                        jsItemY.Add("value", "1");
                        jsItemY.Add("id", strInputName + "_Y");
                        jsItems.Add("1", jsItemY);
                        //添加 否（0）
                        JavaScriptObject jsItemN = new JavaScriptObject();
                        jsItemN.Add("text", "否");
                        jsItemN.Add("value", "0");
                        jsItemN.Add("id", strInputName + "_N");
                        jsItems.Add("2", jsItemN);
                    }
                    else
                    {
                        //如果不是自动添加，则动态读取数据库，读出默认值
                        //根据可选值类型，找到所有的可选值，并以此将这些可选值添加到item里
                        int m_intFormInputValueType = FormInputValueTypeId.ToString().ToInt();
                        FormInputValueTypeInfo m_FormInputValueTypeInfo;
                        if (m_intFormInputValueType > 0 && (m_FormInputValueTypeInfo = new FormInputValueTypeManage().GetInfoById(m_intFormInputValueType)) != null)
                        {
                            foreach (FormInputValueInfo info in (new FormInputValueManage()).GetListByCondition(0, " and FormInputValueTypeId=" + m_FormInputValueTypeInfo.FormInputValueTypeId, " DisplayOrder asc"))
                            {
                                JavaScriptObject jsItem = new JavaScriptObject();
                                jsItem.Add("text", info.Name);
                                jsItem.Add("value", info.FormInputValueId);
                                jsItem.Add("id", strInputName + "_" + info.FormInputValueId);
                                jsItems.Add(info.FormInputValueId.ToString(), jsItem);
                            }
                        }
                    }
                    oJsObj.Add("item", jsItems);
                    #endregion
                    break;
                case "select":
                    // 如果是select类型的form元素，则给JSObject添加options元素，options存放着可选值
                    // 如果字段类型是 bit,则添加 是 否
                    // 如果字段类型不是 bit 则动态读取数据库，读出制定的可选值类型，如果级数>1 ，则会牵扯到动态select的问题，但是此功能因为外部原因并未在前台页面上体现出来，所以尚未测试，在这里特作说明
                    // 这里仅仅是对代码做了简单的逻辑梳理和代码调整，为以后的代码修复提供便捷
                    #region select的详细代码
                    JavaScriptObject jsOptions = new JavaScriptObject();
                    if (FieldTypeStr.ToString() == "bit")
                    {
                        //添加 是（1）
                        JavaScriptObject jsOptionY = new JavaScriptObject();
                        jsOptionY.Add("text", "是");
                        jsOptionY.Add("value", "1");
                        jsOptions.Add("1", jsOptionY);
                        //添加 否（0）
                        JavaScriptObject jsOptionN = new JavaScriptObject();
                        jsOptionN.Add("text", "否");
                        jsOptionN.Add("value", "0");
                        jsOptions.Add("2", jsOptionN);
                    }
                    else
                    {
                        int m_intFormInputValueType = FormInputValueTypeId.ToString().ToInt();
                        FormInputValueTypeInfo m_FormInputValueTypeInfo;
                        if (m_intFormInputValueType > 0 && (m_FormInputValueTypeInfo = new FormInputValueTypeManage().GetInfoById(m_intFormInputValueType)) != null)
                        {
                            JavaScriptObject jsAttr = new JavaScriptObject();
                            jsAttr.Add("valuetypeid", m_FormInputValueTypeInfo.FormInputValueTypeId);
                            jsAttr.Add("step", m_FormInputValueTypeInfo.Step);
                            if (m_FormInputValueTypeInfo.Step > 1)
                            {
                                strInputId += "_" + m_FormInputValueTypeInfo.Step;
                                jsAttr.Add("onchange", "getNextValue(this.id);");
                                oStrBuild.AppendLine("<script>");
                                oStrBuild.AppendLine(" $(document).ready(function() {");
                                oStrBuild.AppendLine(" $(\"#" + strInputId + "\").change();");
                                #region
                                if (DefaultValue.ToString().IndexOf(",") > 0)
                                {
                                    string[] arr = DefaultValue.ToString().Split(',');
                                    DefaultValue = arr[0];
                                    for (int i = 1; i < arr.Length; i++)
                                    {
                                        string strChildName = strInputName + "_" + (m_FormInputValueTypeInfo.Step - i);
                                        oStrBuild.AppendLine("$(\"#" + strChildName + " \").val(" + arr[i] + ");  ");
                                        oStrBuild.AppendLine(" $(\"#" + strChildName + "\").change();");
                                    }
                                }
                                #endregion
                                oStrBuild.AppendLine(" });");
                                oStrBuild.AppendLine("</script>");
                            }
                            oJsObj.Add("attr", jsAttr);
                            foreach (FormInputValueInfo info in (new FormInputValueManage()).GetListByCondition(0, " and ParentId=0  and FormInputValueTypeId=" + m_FormInputValueTypeInfo.FormInputValueTypeId, " DisplayOrder asc"))
                            {
                                JavaScriptObject jsOption = new JavaScriptObject();
                                jsOption.Add("text", info.Name);
                                jsOption.Add("value", info.FormInputValueId);
                                jsOptions.Add(info.FormInputValueId.ToString(), jsOption);
                            }
                        }
                    }
                    oJsObj.Add("options", jsOptions);
                    #endregion
                    break;
                case "checkbox":
                    // 如果是select类型的form元素，则给JSObject添加options元素，options存放着可选值
                    // 如果字段类型是 bit,则添加 是 否
                    // 如果字段类型不是 bit 则动态读取数据库，读出制定的可选值类型，如果级数>1 ，则会牵扯到动态select的问题，但是此功能因为外部原因并未在前台页面上体现出来，所以尚未测试，在这里特作说明
                    // 这里仅仅是对代码做了简单的逻辑梳理和代码调整，为以后的代码修复提供便捷
                    #region select的详细代码
                    JavaScriptObject jsCheckBopOptions = new JavaScriptObject();
                    int m_intFormInputCheckBoxValueType = FormInputValueTypeId.ToString().ToInt();
                    FormInputValueTypeInfo m_FormInputCheckBoxValueTypeInfo;
                    if (m_intFormInputCheckBoxValueType > 0 && (m_FormInputCheckBoxValueTypeInfo = new FormInputValueTypeManage().GetInfoById(m_intFormInputCheckBoxValueType)) != null)
                    {
                        JavaScriptObject jsAttr = new JavaScriptObject();
                        jsAttr.Add("valuetypeid", m_FormInputCheckBoxValueTypeInfo.FormInputValueTypeId);
                        oJsObj.Add("attr", jsAttr);
                        foreach (FormInputValueInfo info in (new FormInputValueManage()).GetListByCondition(0, " and ParentId=0  and FormInputValueTypeId=" + m_FormInputCheckBoxValueTypeInfo.FormInputValueTypeId, " DisplayOrder asc"))
                        {
                            JavaScriptObject jsOption = new JavaScriptObject();
                            jsOption.Add("text", info.Name);
                            jsOption.Add("value", info.FormInputValueId);
                            jsCheckBopOptions.Add(info.FormInputValueId.ToString(), jsOption);
                        }
                    }
                    oJsObj.Add("options", jsCheckBopOptions);
                    #endregion
                    break;
                case "ckeditor":
                    //给Ckeditor增加长宽的设置
                    #region Ckeditor的详细代码
                    oJsObj.Add("height", "300");
                    oJsObj.Add("width", "100%");
                    #endregion
                    break;
                case "contentlink":
                    //增加内容链接的宽度设置
                    oJsObj.Add("width", "90");
                    break;
                case "userdefinedlink":
                    //关联多个可选值
                    oJsObj.Add("width", "90");
                    oJsObj.Add("valuetypeid", FormInputValueTypeId);
                    break;

                case "text":
                    //text 最大限制 采集器 输入限制 等属性
                    #region text的详细代码
                    //如果字段不是text，则添加最大字数的限制
                    if (FieldTypeStr.ToString() != "text")
                    {
                        oJsObj.Add("maxlength", FieldLength.ToString());
                    }
                    oJsObj.Add("style", "width:80%;");
                    //录入采集器
                    if (FieldInputPicker.ToString() != "")
                    {
                        oJsObj.Add("inputpicker", FieldInputPicker);
                    }
                    //添加输入限制
                    AddLimitInfo(oJsObj, FormInputLimitTypeId.ToString().ToInt());
                    #endregion
                    break;
                case "textarea":
                    //  最大限制 宽度 rows 输入限制 等属性
                    #region textarea 的详细代码
                    //如果字段不是text，则添加最大字数的限制
                    if (FieldTypeStr.ToString() != "text")
                        oJsObj.Add("valuelength", FieldLength);
                    oJsObj.Add("style", "width:80%;");
                    oJsObj.Add("rows", "5");//设置textarea的行数
                    AddLimitInfo(oJsObj, FormInputLimitTypeId.ToString().ToInt());
                    #endregion
                    break;
                default:
                    break;
            }
            //添加元素的HTML代码
            oStrBuild.AppendLine(FormAssist.AddFormElement(strInputName, strInputId, DefaultValue.ToString().Replace("''", "'"), oJsObj));
            return oStrBuild.ToString();
        }

        /// <summary>
        /// 为JavaScriptObject 添加输入限制
        /// </summary>
        /// <param name="oJsObj"></param>
        /// <param name="intFormInputLimitTypeId"></param>
        private void AddLimitInfo(JavaScriptObject oJsObj, int intFormInputLimitTypeId)
        {
            FormInputLimitTypeInfo oFormInputLimitTypeInfo = (new FormInputLimitTypeManage()).GetInfoByIdFromCache(intFormInputLimitTypeId);
            if (oFormInputLimitTypeInfo != null)
            {
                oJsObj.Add("RegStr", oFormInputLimitTypeInfo.RegStr);
                oJsObj.Add("RegTip", oFormInputLimitTypeInfo.Name);
            }
        }

        #endregion
    }
}
